import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {AliyunOssOutputUrl, tuikeSystemUrl} from "../../../../config/api";
import {HttpService} from "../../../lib/service/http.service";
import {Headers, RequestOptions} from "@angular/http";
import * as moment from 'moment';
import {Router} from "@angular/router";
import {NzMessageService} from 'ng-zorro-antd';

import {
  FormBuilder,
  FormGroup,
  Validators,
  FormControl
} from '@angular/forms';

import {ModalDirective} from 'ngx-bootstrap';


@Component({
  selector: 'add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.scss']
})
export class AddComponent implements OnInit {

  @ViewChild('addModal') public addModal: ModalDirective;

  validateForm: FormGroup;
  constructor(
    private httpService: HttpService,
    private el: ElementRef,
    private router: Router,
    private fb: FormBuilder,
    private _message: NzMessageService) {

  }
  ngOnInit() {
    this.validateForm = this.fb.group({
      kefu_type: [ 1, [ Validators.required ] ],
      kefu_status: [ 1, [ Validators.required ] ]
    });
    this.getCustomer();
  }

  _submitForm() {
    const controls = this.validateForm.controls;
    for (const i in controls) {
      controls[ i ].markAsDirty();
    }
    const kefu_status = controls.kefu_status.value;
    const kefu_type = controls.kefu_type.value;
    const json = {
      key: "kefu_type",
      value: kefu_type
    };
    const url = tuikeSystemUrl + '/api/v1/admin/setting/change_value';

    let loadlen = 0;
    this.httpService.httpPostAuth(url, json).subscribe(res => {
      if (res.code == 200) {
        loadlen++;
        if (loadlen == 2) {
          this._message.create('success', `保存成功`);
        }
      }
    });

    const json1 = {
      key: "kefu_status",
      value: kefu_status
    };

    this.httpService.httpPostAuth(url, json1).subscribe(res => {
      if (res.code == 200) {
        loadlen++;
        if (loadlen == 2) {
          this._message.create('success', `保存成功`);
        }
      }
    });
  }

  getCustomer(){
    const url = tuikeSystemUrl + '/api/v1/admin/setting/get_kefu_setting';
    this.httpService.httpGetAuth(url).subscribe(res => {
      if (res.code === 200) {
        if (res.data.length == 0) {

        }else {
          const json = {};
          res.data.forEach(item => {
            json[item.key] = item.value;
          });
          this.validateForm.patchValue(json);
        }
      }
    });
  }

  getFormControl(name) {
    return this.validateForm.controls[ name ];
  }


}
